import { gLogin } from "./funcs";

const log = require("@/utils/log.js");
// 获取当前访问路由
const getCurrentUrl = () => {
  const pages = getCurrentPages();
  const pageLen = pages.length;
  if (pageLen) {
    const currentPage = pages[pageLen - 1];
    return `/${currentPage.route}`;
  }
  return "";
};

// 过滤异常参数
const dealErrorArgs = (obj) => {
  const { data = {}, url } = obj;
  if (Object.prototype.toString.call(data) !== "[object Object]") return data;
  let hasErrorArgs = false;
  const filterErrorArgs = Object.keys(data).reduce((total, keys) => {
    const value = data[keys];
    !["undefined", "null", undefined].includes(value) ? (total[keys] = value) : (hasErrorArgs = true);
    return total;
  }, {});

  hasErrorArgs && log.warn(`反馈信息：${url}的参数异常=>${JSON.stringify(data)}`);
  return filterErrorArgs;
};

function request(obj) {
  uni.showLoading({
    title: "加载中"
  });
  return new Promise((resolve, reject) => {
    uni.request({
      url: obj.url, method: obj.method, data: dealErrorArgs(obj), header: {
        "content-type": "application/json;" // 默认值
      }, success(res) {
        console.log(obj["url"], "接口名称");
        console.log(obj["data"], "接口传参");
        console.log(res, "返回数据");
        resolve(res.data);
        uni.hideLoading();
      }, fail(res) {
        uni.hideLoading(); // reject(false)
        wx.showToast({
          title: "网络错误", icon: "none"
        });
        reject();
      }, complete(e) {
        // console.log(e,"http",e.statusCode)
        uni.hideLoading();
        if (e.statusCode > 400) {
          log.warn(`反馈信息:url为:${obj.url},参数为:${JSON.stringify(obj.data)},异常信息:${e.data.msg}`);
          // console.log(`反馈信息:url为:${ obj['url'] },参数为:${JSON.stringify(obj['data']) },异常信息:${e.data.msg}`);
        }
      }
    });
  });
}

function get(obj) {
  return request({ url: obj.url, method: "GET", data: obj.data });
}

function post(obj) {
  return request({ url: obj.url, method: "POST", data: obj.data });
}

function filePost(obj) {
  return new Promise((resolve, reject) => {
    uni.uploadFile({
      url: obj.url, header: {
        token: uni.getStorageSync("yl-token"), app: 1, platform: 2
      }, filePath: obj.filePath, name: "file", formData: obj.data, success(res) {
        uni.hideNavigationBarLoading();
        resolve(res.data);
      }, fail(res) {
        uni.hideNavigationBarLoading(); // reject(false)
      }, complete() {
        uni.hideNavigationBarLoading();
      }
    });
  });
}

async function getFileStream(obj) {
  return new Promise(function(resolve) {
    wx.request({
      url: obj.url, method: "GET", data: obj.data, header: {
        "content-type": "application/x-www-form-urlencoded", // 默认值
        token: uni.getStorageSync("yl-token"), app: 1, platform: 2
      }, responseType: "arraybuffer", success(res) {
        if (res.statusCode == 200) {
          const filename = decodeURIComponent(res.header.filename);
          resolve({ data: res.data, filename: filename || "文件" });
        } else {
          // isShowError ? util.showError('系统繁忙，请稍后在试(' + res.statusCode + ')') : '';
          isShowError ? wx.showToast({
            title: "请求失败，请稍后再试"
          }) : "";
        }
      },

      fail(res) {
        console.log(res);
        // util.showError('请求失败，请稍后再试');
        isShowError ? wx.showToast({
          title: "请求失败，请稍后再试"
        }) : "";
      },

      complete(res) {
        wx.hideLoading();
      }
    });
  });
}

export { request, get, filePost, post, getFileStream };
